/**
 * @Author: songgh
 * @Date: 2021-09-20 14:41:08
 * @LastEditors: songgh
 * @LastEditTime: 2021-09-20 15:41:08
 * @Description: 服务填报
 */
import { defineComponent, onMounted, reactive, watch } from "vue";
import { default as dayjs } from "dayjs";
import { upload, plannerSearch, IUploadData, getRegionData, serviceSearch } from "@src/api";
import { useStore } from "vuex";
import { Dialog, Toast, ImagePreview } from 'vant';
import { useRouter } from "vue-router";

interface IState {
  serviceType?: string;
  city?: string;
  country?: string;
  villages?: string;
  serviceTypeColumns?: Array<string>;
  serviceRegionColumns?: Array<string>;
  serviceCommunityColumns?: Array<string>;
  showPicker?: boolean;
  showType?: string;
  serviceDate?: String;
  serviceDuration?: number;
  serviceContent?: string;
  problem?: string;
  advise?: string;
  imgFileList?: Array<File> | Array<string>;
  planner?: string;
  regionData?: object;
  id?: any;
  isDetailFlag?: boolean;
}

export default defineComponent({
  name: "ServiceForm",
  setup() {
    const router = useRouter();
    const store = useStore();

    const state = reactive<IState>({
      serviceType: "",
      serviceTypeColumns: ["专业咨询", "沟通协调", "宣传服务", "技术把控"],
      serviceRegionColumns: [],
      serviceCommunityColumns: [],
      showPicker: false,
      city: "",
      country: "",
      villages: "",
      showType: "",
      serviceDate: dayjs().format("YYYY.MM.DD"),
      serviceDuration: 0,
      serviceContent: "",
      problem: "",
      advise: "",
      imgFileList: [],
      planner: '',
      regionData: {},
      id: router.currentRoute.value.query?.id,
      isDetailFlag: false,
    });

    state.isDetailFlag = !!state.id; // /^\/service\-detail\/[a-zA-Z0-9]+$/.test(router.currentRoute.value.path);

    onMounted(async () => {
      try {
        if (state.isDetailFlag) {
          Toast.loading({ message: '加载中...', forbidClick: true, });
          const { content: [serviceData] } = await serviceSearch({ id: state.id });
          state.city = serviceData?.city;
          state.serviceContent = serviceData?.content;
          state.country = serviceData?.country;
          state.imgFileList = !serviceData.imgIds || Object.keys(serviceData.imgIds).length == 0 ? [] : serviceData.imgIds;
          state.planner = serviceData?.planner;
          state.problem = serviceData?.problem;
          state.serviceDuration = serviceData?.serviceDuration;
          state.serviceType = serviceData?.serviceType;
          state.advise = serviceData?.suggestion;
          state.villages = serviceData?.villages;
          if (serviceData?.serviceEndTime === serviceData?.serviceStartTime) {
            state.serviceDate = dayjs(serviceData?.serviceStartTime).format("YYYY.MM.DD");
          } else {
            state.serviceDate = `${dayjs(serviceData?.serviceStartTime).format("YYYY.MM.DD")} - ${dayjs(serviceData?.serviceEndTime).format("YYYY.MM.DD")}`;
          }
        } else {
          const { userName } = await store.getters["user/getUserInfo"];
          const { content: [plannerInfo] } = await plannerSearch({ planner: userName });
          state.planner = userName;
          state.country = plannerInfo?.country;
          state.city = plannerInfo?.city;
          state.villages = plannerInfo?.villages;
          state.regionData = (await getRegionData()) || [];
          state.serviceRegionColumns = Object.keys(state.regionData);
        }
      } catch (error) {
        console.error(error);
      }
    });

    watch(() => state.city, () => {
      if(!state.isDetailFlag){
        state.serviceCommunityColumns = state.city ? state.regionData[state.city] : [];
        state.country = '';
      }
    });

    const onSubmit = async (values) => {
      // if (state.imgFileList.length == 0) { Dialog({ message: '请选择图片上传' }); return; }
      const [serviceStartTime, serviceEndTime] = values.serviceDate.split('-');
      const formData = new FormData();
      if (state.imgFileList.length) {
        // @ts-ignore
        formData.append('imgs', state.imgFileList[0].file);
      }
      const data: IUploadData = {
        planner: state.planner,
        city: values.city,
        content: values.serviceContent,
        country: values.country,
        imgs: formData,
        problem: values.problem,
        serviceDuration: `${values.serviceDuration}`,
        serviceStartTime: `${dayjs(serviceStartTime).unix()}`,
        serviceEndTime: serviceEndTime ? dayjs(serviceEndTime).add(1, 'day').subtract(1,'second').unix().toString() : dayjs(serviceStartTime).add(1, 'day').subtract(1,'second').unix().toString(),
        serviceType: values.serviceType,
        suggestion: values.advise,
        villages: values.villages,
      };

      try {
        Toast.loading({ message: '加载中...', forbidClick: true });
        await upload(data);
        router.push('/home');
      } catch (error) {
        console.error(error);
      }
    };

    const onConfirm = (type: string, value: any) => {
      if (type === "serviceDate") {
        const start: string = dayjs(value[0]).format("YYYY.MM.DD");
        const end: string = dayjs(value[1]).format("YYYY.MM.DD");
        state[type] = start === end ? start : `${start} - ${end}`;
      } else {
        switch (type) {
          case 'serviceType': state.serviceType = value; break;
          case 'serviceRegion': state.city = value; break;
          case 'serviceCommunity': state.country = value; break;
          default: break;
        }
      }
      state.showPicker = false;
    };

    const onOversize = (file) => {
      if (file?.size > 5 * 1024 * 1024) {
        Dialog({ message: '图片大小不能超过5M' });
        return true;
      }
      return false;
    };

    const handlerShow = (type: string) => {
      if (state.isDetailFlag) return;
      state.showPicker = true;
      state.showType = type;
    };

    return {
      state,
      onSubmit,
      onConfirm,
      onOversize,
      handlerShow,
    }
  },
  render() {
    return (
      <div>
        <shell title="服务信息填报" v-slots={{
          default: () => (
            <>
              <div class="text-xs">
                {
                  !this.state.isDetailFlag ? <div class="px-3 py-3">
                    <span class="text-gray-400 block mb-2">请填写服务信息</span>
                    <van-uploader v-model:modelValue={this.state.imgFileList} accept=".png,.jpg,.gif;" multiple max-count={1} max-size={this.onOversize} />
                    <span class="text-gray-400 block">
                      只支持JPG、PNG、GIF，大小不超过5M
                    </span>
                  </div> :
                    <div class="px-3 py-3">
                      <span class="text-gray-400 block mb-2">服务图片</span>
                      <van-image
                        width="5rem"
                        height="5rem"
                        fit="cover"
                        src={`${this.state.imgFileList[0]}`}
                        // @ts-ignore
                        onClick={() => { Boolean(this.state.imgFileList[0]) ? ImagePreview(this.state.imgFileList) : null }}
                      />
                    </div>
                }
              </div>
              <van-form onSubmit={this.onSubmit} label-align="right" label-width="4.5rem">
                <van-field
                  disabled={this.state.isDetailFlag}
                  readonly
                  required
                  clickable
                  name="serviceType"
                  modelValue={this.state.serviceType}
                  label="服务类型"
                  placeholder="请选择"
                  class="mb-1"
                  onClick={() => this.handlerShow("serviceType")}
                  rules={[{ required: true, message: '请选择服务类型' }]}
                />
                <van-field
                  disabled={this.state.isDetailFlag}
                  clickable
                  readonly
                  required
                  name="city"
                  modelValue={this.state.city}
                  label="服务地区"
                  placeholder="请选择县区（市）"
                  rules={[{ required: true, message: '请选择市县区' }]}
                  onClick={() => this.handlerShow("serviceRegion")}
                />
                <van-field
                  disabled={this.state.isDetailFlag}
                  clickable
                  readonly
                  required
                  name="country"
                  modelValue={this.state.country}
                  label="服务街道"
                  placeholder="请选择乡镇（街道）"
                  onClick={() => this.handlerShow("serviceCommunity")}
                  rules={[{ required: true, message: '请选择街道镇' }]}
                />
                <van-field
                  disabled={this.state.isDetailFlag}
                  clickable
                  name="villages"
                  v-model:modelValue={this.state.villages}
                  label="服务社区"
                  placeholder={this.state.isDetailFlag ? '' : "请输入村（社区）"}
                  formatter={value => value.replace(/^[\s|\n|\r]*(.*)[\s|\n|\r]*$/, "$1")}
                  class="mb-1"
                />
                <van-field
                  disabled={this.state.isDetailFlag}
                  readonly
                  clickable
                  required
                  name="serviceDate"
                  modelValue={this.state.serviceDate}
                  label="服务时间"
                  placeholder="请选择"
                  onClick={() => this.handlerShow("serviceDate")}
                />
                <van-field
                  disabled={this.state.isDetailFlag}
                  clickable
                  required
                  name="serviceDuration"
                  type="digit"
                  v-model:modelValue={this.state.serviceDuration}
                  label="服务时长"
                  placeholder="请输入"
                  class="mb-1"
                  rules={[{ required: true, validator: val => /^[1-9]\d*$/.test(val), message: '请正确填写服务时长' }]}
                  v-slots={{
                    extra: () => (<span class="text-gray-300 text-sm text-center">小时</span>)
                  }}
                />
                <van-field
                  disabled={this.state.isDetailFlag}
                  v-model:modelValue={this.state.serviceContent}
                  required
                  name="serviceContent"
                  autosize
                  label="服务内容"
                  type="textarea"
                  placeholder="请输入50字以上内容描述"
                  formatter={value => value.replace(/^[\s|\n|\r]*(.*)[\s|\n|\r]*$/, "$1")}
                  rules={[{ required: true, pattern: /.{50,300}/, message: '请输入至少50字' }]}
                  maxlength="300"
                  show-word-limit
                />
                <van-field
                  disabled={this.state.isDetailFlag}
                  v-model:modelValue={this.state.problem}
                  name="problem"
                  rows="1"
                  autosize
                  label="存在问题"
                  type="textarea"
                  placeholder={this.state.isDetailFlag ? '' : "请输入"}
                  formatter={value => value.replace(/^[\s|\n|\r]*(.*)[\s|\n|\r]*$/, "$1")}
                  maxlength="300"
                />
                <van-field
                  disabled={this.state.isDetailFlag}
                  v-model:modelValue={this.state.advise}
                  name="advise"
                  rows="1"
                  autosize
                  label="意见建议"
                  type="textarea"
                  placeholder={this.state.isDetailFlag ? '' : "请输入"}
                  formatter={value => value.replace(/^[\s|\n|\r]*(.*)[\s|\n|\r]*$/, "$1")}
                  maxlength="300"
                />
                <van-popup show={this.state.showPicker} position="bottom">
                  {["serviceType", "serviceCommunity", "serviceRegion"].includes(
                    this.state.showType
                  ) ? (
                    <van-picker
                      show-toolbar
                      columns={this.state[`${this.state.showType}Columns`]}
                      onConfirm={(value) => this.onConfirm(this.state.showType, value)}
                      onCancel={() => (this.state.showPicker = false)}
                    />
                  ) : this.state.showType === "serviceDate" ? (
                    <van-calendar
                      poppable={false}
                      min-date={new Date(1970, 1, 1)}
                      max-date={new Date()}
                      default-date={this.state.serviceDate.split('-').map(d => new Date(d))}
                      show-title={false}
                      style={{ height: "30rem" }}
                      type="range"
                      allow-same-day
                      onConfirm={(date) => this.onConfirm("serviceDate", date)}
                    />
                  ) : (
                    <></>
                  )}
                </van-popup>
                <van-button
                  block
                  type="primary"
                  native-type="submit"
                  round={false}
                  class="mx-3 my-3"
                  style={{ display: this.state.isDetailFlag ? 'none' : 'block', width: 'calc(100% - 1.5rem)' }}
                >
                  发布
                </van-button>
              </van-form>
            </>
          )
        }}>
        </shell>
      </div>
    );
  }
});
